#! /bin/bash

set -e

OBS_MODEL_URL=$1

sed -i -e 's/^#Port 22/Port 5000/' -e 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config && systemctl restart sshd

FILE=`basename ${OBS_MODEL_URL}` && FILE_NAME=${FILE%.*}

OBS_BUCKET_NAME=`echo ${OBS_MODEL_URL} | sed -e 's|^[^/]*//||' -e 's|/.*$||' | awk -F '.' '{print $1}'`

OBS_BUCKET_PATH=`echo ${OBS_MODEL_URL} | cut -d '/' -f4- | sed "s/${FILE}//"`

mkdir -p /opt/atc/{model,output} /opt/msame/output

wget -O /opt/atc/model/${FILE_NAME}.pb ${OBS_MODEL_URL}

source /root/.bashrc && atc --model="/opt/atc/model/${FILE_NAME}.pb" --framework=3 --output="/opt/atc/output/${FILE_NAME}" --soc_version="Ascend310" --input_shape="Placeholder:1,224,224,3"

[ -f /root/msame.zip ] && unzip -q -d /usr/local /root/msame.zip && cd /usr/local/msame && chmod +x build.sh && ./build.sh g++ /usr/local/msame/out && ln -s /usr/local/msame/out/msame /usr/local/bin/msame && cd -

rm -rf /opt/msame/output/${FILE_NAME} && msame --model "/opt/atc/output/${FILE_NAME}.om"  --output "/opt/msame/output/${FILE_NAME}" --outfmt TXT --loop 1

MSAME_OUTPUT_FILE=`find /opt/msame/output/${FILE_NAME} -type f -name '*.txt'`

wget -O /root/obsutil.tar.gz https://obs-community.obs.cn-north-1.myhuaweicloud.com/obsutil/current/obsutil_linux_amd64.tar.gz

[[ ! -d /usr/local/obsutil ]] && mkdir /usr/local/obsutil

tar xf /root/obsutil.tar.gz -C /usr/local/obsutil --strip-components 1 && chmod 755 /usr/local/obsutil/obsutil && ln -s /usr/local/obsutil/obsutil /usr/local/bin/obsutil && rm -f /root/obsutil.tar.gz

/sbin/runuser -l root -c 'obsutil config -e="obs.cn-north-4.myhuaweicloud.com"' && [[ -f /root/.obsutilconfig ]] && sed -i 's/^\(autoChooseSecurityProvider=\)false$/\1true/' /root/.obsutilconfig

/sbin/runuser -l root -c "obsutil cp ${MSAME_OUTPUT_FILE} obs://${OBS_BUCKET_NAME}/${OBS_BUCKET_PATH}${FILE_NAME}.txt -f" && rm -rf /opt/atc/model/${FILE_NAME}.pb /opt/atc/output/${FILE_NAME}.om /opt/msame/output/${FILE_NAME}

curl -k -o /usr/local/agent_install.sh https://obs.cn-north-4.myhuaweicloud.com/uniagent-cn-north-4/script/agent_install.sh && bash /usr/local/agent_install.sh && rm -f /usr/local/agent_install.sh
